package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.lkd.entity.Business;
import com.lkd.entity.Node;
import com.lkd.entity.Region;
import com.lkd.mapper.BusinessMapper;
import com.lkd.mapper.NodeMapper;
import com.lkd.mapper.RegionMapper;
import com.lkd.mapper.VendingMachineMapper;
import com.lkd.service.NodeService;
import com.lkd.vo.NodeVo;
import com.lkd.vo.RegionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NodeServiceImpl implements NodeService {
    @Autowired
    private NodeMapper nodeMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private VendingMachineMapper vendingMachineMapper;

    @Override
    public List<Business> getBusinessType() {
        return businessMapper.getBusinessType();
    }

    @Override
    public boolean addNode(Node node) {
        return nodeMapper.addNode(node);
    }

    @Override
    public boolean updateNode(Node node) {
        return nodeMapper.updateNode(node);
    }

    @Override
    public boolean deleteNode(Long nodeId) {
        return nodeMapper.deleteNode(nodeId);
    }


    /**
     * 根据节点ID查找对应的节点信息。
     *
     * @param nodeId 节点的ID
     * @return 返回节点的详细信息，包括所属区域、所属商圈和机器数量
     */
    @Override
    public NodeVo findById(Long nodeId) {

        // 通过节点ID在节点表中查找节点
        Node node = nodeMapper.findById(nodeId);

        // 根据节点所属的区域ID，查询该区域的信息，并转换为区域VO
        Long regionId = node.getRegionId();
        if (regionId == null) {
            return null;
        }
        // 根据区域ID，查询该区域的信息，并转换为区域VO
        Region region = regionMapper.findById(regionId);
        RegionVo regionVo = BeanUtil.copyProperties(region, RegionVo.class);
        //Integer count = nodeMapper.countByRegionId(region.getId());
        //regionVo.setNodeCount(count);

        // 根据节点所属的商圈ID，查询该商圈的信息
        Integer businessId = node.getBusinessId();
        Business business = businessMapper.findById(businessId);

        // 统计该节点下关联的机器数量
        Integer vmCount = vendingMachineMapper.countByNodeId(node.getId());

        // 将节点信息转换为节点VO，并设置区域信息、商圈信息和机器数量
        NodeVo nodeVo = BeanUtil.copyProperties(node, NodeVo.class);
        nodeVo.setRegion(regionVo);
        nodeVo.setBusinessType(business);
        nodeVo.setVmCount(vmCount);

        return nodeVo;
    }
}
